﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;
using umbraco;
using umbraco.BasePages;
using umbraco.BusinessLogic;
using umbraco.interfaces;
using umbraco.controls;
using Commerce.Common;
using System.Data;

namespace CommerceForUmbraco.adminSection.commerce
{
    public partial class dashboardCategorySearch : System.Web.UI.UserControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            this.pane_catsearch.Text = "Search Categories";
            this.pp_catsearch.Text = "Search";

            BindData();
        }

        protected void BindData()
        {
            // get collection values
            Commerce.Common.CategoryCollection categories = null;

            categories = new CategoryCollection().Where("categoryName", SubSonic.Comparison.Like, string.Format("%{0}%", searchText.Text)).OrderByAsc("categoryName").Load();
            //SubSonic.InlineQuery qry = new SubSonic.InlineQuery();
            //products = new ProductCollection();
            //products = qry.ExecuteAsCollection<ProductCollection>(String.Format("select * from dbo.CSK_Store_Product where productname LIKE '%{0}%'", searchText.Text.Trim()));
            //products.Sort("ProductName", true);

            DataTable dt = categories.ToDataTable();

            dt.Columns.Add("Parent");

            foreach (DataRow row in dt.Rows)
            {
                int parentID = 0;
                if (Int32.TryParse(row["ParentID"].ToString(), out parentID))
                {
                    if (parentID > 0)
                    {
                        CategoryController.Load();
                        
                        Category parent = CategoryController.Find(parentID);
                        if (parent != null)
                        {
                            if (parent.IsLoaded)
                            {
                                row["Parent"] = parent.CategoryName;
                            }
                        }
                        else
                        {
                            string oops = "null";
                        }
                    }
                }
            }

            gvCategories.DataSource = dt;
            gvCategories.DataBind();
        }

        protected void searchButton_Click(object sender, EventArgs e)
        {
            BindData();
        }
    }
}